package com.sinosoft.cloud.access.handler;

import com.sinosoft.cloud.access.entity.TranData;
import com.sinosoft.cloud.access.net.MessageObject;
import com.sinosoft.cloud.access.service.AccessServiceBean;
import com.sinosoft.cloud.access.service.AccessServiceGate;
import io.netty.channel.ChannelHandlerContext;

/**
 * cloud-netty
 *
 * @title: cloud-netty
 * @package: com.sinosoft.cloud.access.handler
 * @author: yangming
 * @date: 2017/12/4 下午5:07
 */
public class MicroserviceHandler extends AbstractHandler {
    @Override
    MessageObject dealMessage(ChannelHandlerContext ctx, MessageObject messageObject) {

        if (messageObject.getHasError()){
            return messageObject;
        }

        /*获取服务网关，服务网关是在系统启动时，初始化所有渠道的服务信息，存入缓存中*/
        AccessServiceGate accessServiceGate = AccessServiceGate.getInstance();
        /*根据报文头信息获取对应的服务类*/
        AccessServiceBean accessServiceBean = accessServiceGate.getServiceByTranData(getAccessName(), messageObject.getTranData().getHead());
        /*执行服务类，在服务类中应 应调用微服务信息*/
        TranData returnData = null;
        try {
            returnData = accessServiceBean.service(messageObject.getTranData());
        } catch (Exception e) {
            e.printStackTrace();
            if (returnData == null) {
                returnData = new TranData();
                if (null == returnData.getHead()) {
                    returnData.setHead(messageObject.getTranData().getHead());
                }
                returnData.getHead().setFlag("1");
                returnData.getHead().setDesc("发生严重错误:" + e.getMessage());
                logger.error("发生严重错误:" + e.getMessage());
            }
        }
        messageObject.setTransCode(messageObject.getTranData().getHead().getTransCode());
        messageObject.setTranData(returnData);
        messageObject.setNext(MessageObject.Type.fireChannelRead);
        return messageObject;
    }
}
